package com.zzc.zzcapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.keleclientsdk.client.KeleApiClient;
import com.zzc.zzcapi.common.BaseResponse;
import com.zzc.zzcapi.common.ErrorCode;
import com.zzc.zzcapi.common.ResultUtils;
import com.zzc.zzcapi.exception.BusinessException;
import com.zzc.zzcapi.exception.ThrowUtils;
import com.zzc.zzcapi.mapper.UserInterfaceInfoMapper;
import com.zzc.zzcapi.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.zzc.zzcapi.model.dto.userInterfaceInfo.UserInterfaceInfoAddRequest;
import com.zzc.zzcapi.model.entity.InterfaceInfo;
import com.zzc.zzcapi.model.entity.User;
import com.zzc.zzcapi.model.entity.UserInterfaceInfo;
import com.zzc.zzcapi.model.vo.UserInterfaceInfoVO;
import com.zzc.zzcapi.service.InterfaceInfoService;
import com.zzc.zzcapi.service.UserInterfaceInfoService;
import com.zzc.zzcapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 帖子接口
 *
 * @author 张昭冲
 * 
 */
@RestController
@RequestMapping("/userInterfaceInfo")
@Slf4j
public class UserInterfaceInfoController {

    public static final int DEFAULT_INVOKE_NUM = 10;
    public static final int DEFAULT_STATUS = 0;
    public static final int DEFAULT_TOTAL_NUM = 0;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;
    @Resource
    private UserService userService;
    @Resource
    private KeleApiClient keleApiClient;
    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    UserInterfaceInfoMapper userInterfaceInfoMapper;
    // region 增删改查

    /**
     * 用户请求接口，增加请求记录
     *
     * @param userInterfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserInterfaceInfo(@RequestBody UserInterfaceInfoAddRequest userInterfaceInfoAddRequest, HttpServletRequest request) {
        if (userInterfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取登录用户id
        User loginUser = userService.getLoginUser(request);
        // userid + InterfaceInfoId是否存在
        Long interfaceInfoId = userInterfaceInfoAddRequest.getInterfaceInfoId();
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId()).eq("interfaceInfoId", interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getOne(queryWrapper);
        if(userInterfaceInfo == null) {
            // 创建对象
            userInterfaceInfo.setUserId(loginUser.getId());
            userInterfaceInfo.setInterfaceInfoId(interfaceInfoId);
            userInterfaceInfo.setTotalNum(DEFAULT_TOTAL_NUM);
            userInterfaceInfo.setLeftNum(DEFAULT_INVOKE_NUM);
            userInterfaceInfo.setStatus(DEFAULT_STATUS);
            // 用户-接口信息，保存
            boolean result = userInterfaceInfoService.save(userInterfaceInfo);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            long newInterfaceInfoId = userInterfaceInfo.getId();
            return ResultUtils.success(newInterfaceInfoId);
        }
        userInterfaceInfoMapper.resetCount(interfaceInfoId, loginUser.getId(), DEFAULT_INVOKE_NUM);
        return ResultUtils.success(interfaceInfoId);
    }

    /**
     *
     * @param interfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo interfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);

        // 参数校验
        userInterfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        UserInterfaceInfo oldInterfaceInfo = userInterfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可修改
        if(!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = userInterfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    @PostMapping("/recoverNum")
    public BaseResponse<Boolean> recoverNumInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                         HttpServletRequest request) {
        return null;
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserInterfaceInfoVO> getUserInterfaceInfoVOById(Long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 登录用户信息
        User loginUser = userService.getLoginUser(request);
        // 查询当前接口剩余调用次数
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        queryWrapper.eq("interfaceInfoId", id);
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getOne(queryWrapper);
        UserInterfaceInfoVO userInterfaceInfoVO = new UserInterfaceInfoVO();
        if(interfaceInfo != null) {
            userInterfaceInfoVO.setLeftNum(userInterfaceInfo.getLeftNum());
        }
        return ResultUtils.success(userInterfaceInfoVO);
    }
}
